#include("../layout.html")
#@layout("分类目录")

<!-- 宏定义：递归生成分类下拉选项 -->
#define dropdown(terms, key, depth)
#for(term : terms)
#set(indent = java.lang.String::join("", java.util.Collections::nCopies(depth, "— ")))
<option value="#(term.termId)">#(indent + term.name)</option>
#if(null != term.children)
#@dropdown(term.children, term.termId, depth + 1)
#end
#end
#end

#define body()
<div class="wp-heading-container">
    <h1 class="wp-heading-inline">分类目录</h1>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="refresh-btn">
        <i class="layui-icon layui-icon-refresh"></i> 刷新
    </button>
</div>
<hr class="wp-header-end">

<div class="layui-fluid">
    <!-- 搜索区域 -->
    <form class="layui-form search-form" action="">
        <div class="search-box">
            <label class="screen-reader-text" for="search-input">搜索文章:</label>
            <div class="layui-inline">
                <input type="search" id="search-input" name="s" value="" class="layui-input"
                       placeholder="输入分类名称搜索..." autocomplete="off">
            </div>
            <div class="layui-inline">
                <button type="submit" id="search-submit" class="layui-btn layui-btn-sm layui-btn-primary">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button type="button" id="reset-search" class="layui-btn layui-btn-sm layui-btn-default">
                    <i class="layui-icon layui-icon-close"></i> 重置
                </button>
            </div>
        </div>
    </form>

    <div class="layui-row layui-col-space15">
        <!-- 左侧：添加分类表单 -->
        <div class="layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h2>添加新分类目录</h2>
                </div>
                <div class="layui-card-body">
                    <form class="layui-form tby-form-left" action="/web/admin/term/create" method="post" id="term-form">
                        <input type="hidden" name="taxonomy" value="category">
                        <div class="layui-form-item">
                            <label class="layui-form-label" for="name">名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="name" id="name" required lay-verify="required"
                                       placeholder="请输入分类名称" autocomplete="off" class="layui-input">
                            </div>
                            <div class="layui-form-mid layui-word-aux">这将是它在站点上显示的名字。</div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" for="slug">别名</label>
                            <div class="layui-input-block">
                                <input type="text" name="slug" id="slug" placeholder="分类别名（可选）"
                                       autocomplete="off" class="layui-input">
                            </div>
                            <div class="layui-form-mid layui-word-aux">“别名”是在URL中使用的别称，它可以令URL更美观。通常使用小写，只能包含字母，数字和连字符（-）。</div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" for="parent">父级分类</label>
                            <div class="layui-input-block">
                                <select name="parent" id="parent" lay-search>
                                    <option value="0">无</option>
                                    #@dropdown(terms.getHierarchyTerms(), 0, 0)
                                </select>
                            </div>
                            <div class="layui-form-mid layui-word-aux">分类目录可以有层级关系。例如：可以有"音乐"分类，其下包含"流行"和"古典"子分类。</div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" for="description">描述</label>
                            <div class="layui-input-block">
                                <textarea name="description" id="description" placeholder="分类描述（可选）"
                                          class="layui-textarea" rows="3"></textarea>
                            </div>
                            <div class="layui-form-mid layui-word-aux">描述只会在一部分主题中显示。</div>
                        </div>
                        <div class="layui-form-item">
                            <button type="submit" lay-submit lay-filter="*" class="layui-btn layui-btn-sm layui-btn-normal">
                                <i class="layui-icon layui-icon-add-circle"></i> 添加新分类目录
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧：分类列表 -->
        <div class="layui-col-md8">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h2>分类列表</h2>
                    <div class="card-header-action">
                        <span class="layui-badge layui-bg-blue" id="total-count">0</span>
                    </div>
                </div>
                <div class="layui-card-body">
                    <form id="posts-filter" class="layui-form">
                        #@tableNav("top", "batch-top")

                        <div class="table-container">
                            <table class="layui-table" lay-skin="line" lay-even>
                                <colgroup>
                                    <col width="30">
                                    <col width="200">
                                    <col>
                                    <col width="120">
                                    <col width="80">
                                    <col width="100">
                                </colgroup>
                                <thead>
                                <tr>
                                    <th><input type="checkbox" class="select-all" lay-skin="primary" lay-filter="checkall"></th>
                                    <th>名称</th>
                                    <th>描述</th>
                                    <th>别名</th>
                                    <th>文章数</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <!-- 动态内容将通过模板渲染 -->
                                </tbody>
                                #[[
                                <script type="text/html" id="table-template">
                                    {{# if(d.length === 0){ }}
                                    <tr>
                                        <td colspan="6" class="text-center no-data">
                                            <i class="layui-icon layui-icon-tips"></i> 暂无数据
                                        </td>
                                    </tr>
                                    {{# } }}
                                    {{# layui.each(d, function(index, item){ }}
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="termIds" value="{{item.termId}}" lay-skin="primary" lay-filter="termCheckbox">
                                        </td>
                                        <td>
                                            <div class="term-name-cell">
                                                <strong class="term-name">{{item.name}}</strong>
                                                {{# if(item.parentName){ }}
                                                <span class="parent-term">(父级: {{item.parentName}})</span>
                                                {{# } }}
                                            </div>
                                        </td>
                                        <td>
                                            <div class="term-description">{{item.description || '无描述'}}</div>
                                        </td>
                                        <td>
                                            <code class="term-slug">{{item.slug || '-'}}</code>
                                        </td>
                                        <td>
                                            <span class="layui-badge {{item.count > 0 ? 'layui-bg-blue' : 'layui-bg-gray'}}">
                                                {{item.count || 0}}
                                            </span>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button type="button" class="layui-btn layui-btn-xs layui-btn-normal edit-btn"
                                                        data-id="{{item.termId}}">
                                                    编辑
                                                </button>
                                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger delete-btn"
                                                        data-id="{{item.termId}}" data-name="{{item.name}}">
                                                    删除
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    {{# }); }}
                                </script>
                                ]]#
                            </table>
                        </div>

                        #@tableNav("bottom", "batch-bottom")
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
#end

<!-- 宏定义：表格导航 -->
#define tableNav(position, selectId)
<div class="tablenav #(position)">
    <div class="alignleft actions bulk-actions">
        <label for="#(selectId)" class="screen-reader-text">选择批量操作</label>
        <div class="layui-inline">
            <select name="action" id="#(selectId)" lay-filter="batch-action">
                <option value="-1">批量操作</option>
                <option value="delete">删除</option>
            </select>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary apply-btn">
                应用
            </button>
        </div>
        <div class="layui-inline selected-count">
            已选择 <span class="count">0</span> 项
        </div>
    </div>
    <div class="tablenav-pages layui-inline"></div>
    <br class="layui-clear">
</div>
#end

#define css()
<style>
    .wp-heading-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 15px;
    }

    .search-form {
        background: #f8f8f8;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 15px;
    }

    .search-box {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .layui-card {
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        border-radius: 4px;
    }

    .layui-card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f6f6f6;
    }

    .card-header-action {
        font-size: 14px;
    }

    .term-name-cell {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .parent-term {
        font-size: 12px;
        color: #999;
    }

    .term-description {
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .term-slug {
        background: #f1f1f1;
        padding: 2px 6px;
        border-radius: 3px;
        font-family: monospace;
    }

    .action-buttons {
        display: flex;
        gap: 5px;
    }

    .table-container {
        position: relative;
        min-height: 200px;
    }

    .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
    }

    .no-data {
        text-align: center;
        color: #999;
        padding: 40px !important;
    }

    .no-data .layui-icon {
        font-size: 24px;
        margin-right: 8px;
    }

    .selected-count {
        margin-left: 15px;
        color: #666;
        font-size: 14px;
    }

    .selected-count .count {
        color: #1E9FFF;
        font-weight: bold;
    }

    .text-center {
        text-align: center;
    }

    @media (max-width: 768px) {
        .layui-col-md4, .layui-col-md8 {
            width: 100%;
        }

        .search-box {
            flex-direction: column;
            align-items: stretch;
        }

        .action-buttons {
            flex-direction: column;
        }
    }
</style>
#end

#define foot()
<script>
    layui.define(['laypage', 'tbynet', 'table'], function(exports) {
        'use strict';

        const $ = layui.$;
        const form = layui.form;
        const layer = layui.layer;
        const laytpl = layui.laytpl;
        const laypage = layui.laypage;
        const tbynet = layui.tbynet;
        const table = layui.table;

        /**
         * 分类管理模块
         */
        const TermManager = {
            // 状态管理
            state: {
                keyword: '',
                currentPage: 1,
                pageSize: 20,
                isLoading: false,
                selectedCount: 0
            },

            // API 端点
            endpoints: {
                create: '/web/admin/term/create',
                update: '/web/admin/term/update',
                list: '/web/admin/term/list',
                delete: '/web/admin/term/delete',
                batchDelete: '/web/admin/term/batchDelete'
            },

            /**
             * 初始化模块
             */
            init() {
                this.initEventListeners();
                this.setupFormCallbacks();
                this.loadTermList();
                this.renderStatistics();
            },

            /**
             * 初始化事件监听器
             */
            initEventListeners() {
                // 搜索相关
                $('#search-submit').on('click', (e) => {
                    e.preventDefault();
                    this.handleSearch();
                });

                $('#reset-search').on('click', () => {
                    this.resetSearch();
                });

                $('#search-input').on('keypress', (e) => {
                    if (e.which === 13) {
                        e.preventDefault();
                        this.handleSearch();
                    }
                });

                // 刷新按钮
                $('#refresh-btn').on('click', () => {
                    this.refreshData();
                });

                // 复选框事件
                form.on('checkbox(checkall)', (data) => {
                    this.toggleSelectAll(data.elem.checked);
                });

                form.on('checkbox(termCheckbox)', () => {
                    this.updateSelectionState();
                });

                // 批量操作
                $('.apply-btn').on('click', (e) => {
                    this.handleBulkAction(e.target);
                });

                // 操作按钮事件委托
                $('tbody').on('click', '.edit-btn', (e) => {
                    const termId = $(e.currentTarget).data('id');
                    this.editTerm(termId);
                });

                $('tbody').on('click', '.delete-btn', (e) => {
                    const $target = $(e.currentTarget);
                    const termId = $target.data('id');
                    const termName = $target.data('name');
                    this.deleteTerm(termId, termName);
                });
            },

            /**
             * 设置表单回调
             */
            setupFormCallbacks() {
                // 创建分类成功回调
                tbynet.form[this.endpoints.create] = (data, required, res) => {
                    this.handleCreateSuccess(res);
                };
            },

            /**
             * 处理搜索
             */
            handleSearch() {
                const keyword = $('#search-input').val().trim();
                this.state.keyword = keyword;
                this.loadTermList(1);
            },

            /**
             * 重置搜索
             */
            resetSearch() {
                $('#search-input').val('');
                this.state.keyword = '';
                this.loadTermList(1);
            },

            /**
             * 刷新数据
             */
            refreshData() {
                this.loadTermList(this.state.currentPage);
                layer.msg('数据已刷新', { icon: 1, time: 1000 });
            },

            /**
             * 全选/全不选
             */
            toggleSelectAll(checked) {
                $('input[name="termIds"]').prop('checked', checked);
                this.updateSelectionState();
                form.render('checkbox');
            },

            /**
             * 更新选择状态
             */
            updateSelectionState() {
                const selectedCount = $('input[name="termIds"]:checked').length;
                this.state.selectedCount = selectedCount;

                $('.selected-count .count').text(selectedCount);

                // 更新全选复选框状态
                const totalCount = $('input[name="termIds"]').length;
                const allChecked = totalCount > 0 && selectedCount === totalCount;
                $('.select-all').prop('checked', allChecked);
                form.render('checkbox');
            },

            /**
             * 处理批量操作
             */
            handleBulkAction(buttonElement) {
                const $button = $(buttonElement);
                const action = $button.closest('.bulk-actions').find('select').val();
                const termIds = this.getSelectedTermIds();

                if (action === 'delete') {
                    this.batchDeleteTerms(termIds);
                } else {
                    layer.msg('请选择批量操作', { icon: 2 });
                }
            },

            /**
             * 获取选中的分类ID
             */
            getSelectedTermIds() {
                const termIds = [];
                $('input[name="termIds"]:checked').each(function() {
                    termIds.push($(this).val());
                });
                return termIds;
            },

            /**
             * 编辑分类
             */
            editTerm(termId) {
                window.location.href = `/admin/category/edit?termId=${termId}`;
            },

            /**
             * 删除分类
             */
            deleteTerm(termId, termName) {
                layer.confirm(`确定要删除分类"${termName}"吗？`, {
                    title: '确认删除',
                    btn: ['确定', '取消'],
                    icon: 3
                }, (index) => {
                    layer.close(index);
                    this.executeDelete(termId);
                });
            },

            /**
             * 批量删除分类
             */
            batchDeleteTerms(termIds) {
                if (termIds.length === 0) {
                    layer.msg('请选择要删除的分类目录', { icon: 2 });
                    return;
                }

                layer.confirm(`确定要删除选中的 ${termIds.length} 个分类目录吗？`, {
                    title: '批量删除确认',
                    btn: ['确定', '取消'],
                    icon: 3
                }, (index) => {
                    layer.close(index);
                    this.executeBatchDelete(termIds);
                });
            },

            /**
             * 执行删除
             */
            executeDelete(termId) {
                this.showLoading();

                tbynet.ajax(this.endpoints.delete, {
                    id: termId,
                    taxonomy: 'category'
                }, (res) => {
                    this.hideLoading();
                    this.handleDeleteResult(res);
                }, "json");
            },

            /**
             * 执行批量删除
             */
            executeBatchDelete(termIds) {
                this.showLoading();

                tbynet.ajax(this.endpoints.batchDelete, {
                    termIds: termIds,
                    taxonomy: 'category'
                }, (res) => {
                    this.hideLoading();
                    this.handleDeleteResult(res, true);
                }, "json");
            },

            /**
             * 处理删除结果
             */
            handleDeleteResult(res, isBatch = false) {
                if (res.state) {
                    layer.msg(res.msg, { icon: 1, time: 1500 });
                    // 如果是批量删除或删除后当前页可能为空，则返回第一页
                    const targetPage = isBatch || this.state.currentPage === 1 ? 1 : this.state.currentPage;
                    setTimeout(() => {
                        this.loadTermList(targetPage);
                    }, 1000);
                } else {
                    layer.msg(res.msg || '删除失败', { icon: 2 });
                }
            },

            /**
             * 加载分类列表
             */
            loadTermList(page = 1) {
                if (this.state.isLoading) return;

                this.state.isLoading = true;
                this.state.currentPage = page;

                const params = {
                    taxonomies: 'category',
                    page: page,
                    size: this.state.pageSize
                };

                if (this.state.keyword) {
                    params.search = this.state.keyword;
                }

                this.showLoading();

                tbynet.ajax(this.endpoints.list, params, (res) => {
                    this.state.isLoading = false;
                    this.hideLoading();
                    this.renderTermList(res.data);
                    this.renderStatistics(res.data);
                }, "json");
            },

            /**
             * 显示加载状态
             */
            showLoading() {
                if ($('.loading-overlay').length === 0) {
                    $('.table-container').append(`
                        <div class="loading-overlay">
                            <div class="loading-content">
                                <i class="layui-icon layui-icon-loading layui-anim-rotate"></i>
                                <div>加载中...</div>
                            </div>
                        </div>
                    `);
                }
            },

            /**
             * 隐藏加载状态
             */
            hideLoading() {
                $('.loading-overlay').remove();
            },

            /**
             * 渲染分类列表
             */
            renderTermList(data) {
                const $template = $('#table-template');
                if ($template.length === 0) return;

                const terms = data.terms || [];

                laytpl($template.html()).render(terms, (html) => {
                    $('table tbody').html(html);
                    this.renderPagination(data.total);
                    this.updateSelectionState();
                    form.render();
                });
            },

            /**
             * 渲染分页
             */
            renderPagination(total) {
                const $paginationContainer = $('.tablenav-pages');

                if (total <= this.state.pageSize) {
                    $paginationContainer.html('');
                    return;
                }

                laypage.render({
                    elem: $paginationContainer[0],
                    count: total,
                    limit: this.state.pageSize,
                    curr: this.state.currentPage,
                    layout: ['count', 'prev', 'page', 'next', 'skip'],
                    jump: (obj, first) => {
                        if (!first) {
                            this.loadTermList(obj.curr);
                        }
                    }
                });
            },

            /**
             * 渲染统计信息
             */
            renderStatistics(data = null) {
                if (data && data.total) {
                    $('#total-count').text(data.total);
                }
            },

            /**
             * 处理创建成功
             */
            handleCreateSuccess(res) {
                layer.msg(res.msg, {
                    icon: 1,
                    time: 1500
                }, () => {
                    $('#term-form')[0].reset();
                    this.loadTermList(1);
                    form.render();
                });
            }
        };

        // 初始化分类管理
        $(document).ready(() => {
            TermManager.init();
        });

        // 提供全局访问
        window.TermManager = TermManager;
        exports('category', TermManager);
    });
</script>
#end